//
//  ChartMarkerImage.swift
//  Charts
//
//  Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
//  A port of MPAndroidChart for iOS
//  Licensed under Apache License 2.0
//
//  https://github.com/danielgindi/Charts
//

import Foundation
import CoreGraphics

@objc(ChartMarkerImage)
open class MarkerImage: NSObject, Marker
{
    /// The marker image to render
    @objc open var image: NSUIImage?
    
    open var offset: CGPoint = CGPoint()
    
    @objc open weak var chartView: ChartViewBase?
    
    /// As long as size is 0.0/0.0 - it will default to the image's size
    @objc open var size: CGSize = CGSize()
    
    
    @objc open var color: UIColor
    @objc open var arrowSize = CGSize(width: 15, height: 11)
    @objc open var font: UIFont
    @objc open var textColor: UIColor
    @objc open var insets: UIEdgeInsets
    @objc open var minimumSize = CGSize()
    
    fileprivate var label: NSMutableAttributedString?
    fileprivate var _labelSize: CGSize = CGSize()
    fileprivate var _paragraphStyle: NSMutableParagraphStyle?
    fileprivate var _drawAttributes = [NSAttributedString.Key : Any]()
    
    
    @objc public init(color: UIColor, font: UIFont, textColor: UIColor, insets: UIEdgeInsets)
    {
        self.color = color
        self.font = font
        self.textColor = textColor
        self.insets = insets
        
        _paragraphStyle = NSParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle
        _paragraphStyle?.alignment = .center
        super.init()
    }
    
    
    
    //    public override init()
    //    {
    //        super.init()
    //    }
    
    open func offsetForDrawing(atPoint point: CGPoint) -> CGPoint
    {
        var offset = self.offset
        var size = self.size
        
        if size.width == 0.0 && image != nil
        {
            size.width = image!.size.width
        }
        if size.height == 0.0 && image != nil
        {
            size.height = image!.size.height
        }
        
        let width = size.width
        let height = size.height
        let padding: CGFloat = 8.0
        
        var origin = point
        origin.x -= width / 2
        origin.y -= height
        
        if origin.x + offset.x < 0.0
        {
            offset.x = -origin.x + padding
        }
        else if let chart = chartView,
                origin.x + width + offset.x > chart.bounds.size.width
        {
            offset.x = chart.bounds.size.width - origin.x - width - padding
        }
        
        if origin.y + offset.y < 0
        {
            offset.y = height + padding;
        }
        else if let chart = chartView,
                origin.y + height + offset.y > chart.bounds.size.height
        {
            offset.y = chart.bounds.size.height - origin.y - height - padding
        }
        
        return offset
    }
    
    open func refreshContent(entry: ChartDataEntry, highlight: Highlight)
    {

        setLabel(entry)

    }
    
    @objc open func setLabel(_ entry: ChartDataEntry)
    {
//        label = NSMutableAttributedString(string: newLabel)
        
        _drawAttributes.removeAll()
        _drawAttributes[.font] = self.font
        _drawAttributes[.paragraphStyle] = _paragraphStyle
        _drawAttributes[.foregroundColor] = self.textColor
        
//        _labelSize = label?.size(withAttributes: _drawAttributes) ?? CGSize.zero
        
        var num1 = NSDecimalNumber(value: entry.param1)
        let num2 = NSDecimalNumber(10000)
        
        
        // 除法运算（需要指定保留位数）
        let scale = 1 // 设置保留四位小数
        var handler = NSDecimalNumberHandler(roundingMode: .plain, scale: Int16(scale), raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
        let result = num1.dividing(by: num2, withBehavior: handler)
        print("两个小数相除结果：\(result)")
        
    
        
        let str = String(format: "均价%.1f万", Double(entry.param1) / Double(10000.0))

        var str1 = ""
        if entry.param2 > 0 {
            str1 = String(format: "较上期涨%.1f万", entry.param2/10000.0)
        }
        else if entry.param2 == 0 {
            str1 = "较上期持平"
        }
        else{
            str1 = String(format: "较上期降%.1f万", entry.param2/10000.0)
        }
        
        let paragraphStyle = ParagraphStyle.default.mutableCopy() as! MutableParagraphStyle
        paragraphStyle.lineBreakMode = .byTruncatingTail
        paragraphStyle.alignment = .center
        paragraphStyle.lineSpacing = 6
        
        label = NSMutableAttributedString(string: "\(str)\n\(str1)")
        label?.addAttributes([.foregroundColor:UIColor.white,.font:self.font,.paragraphStyle:paragraphStyle], range:NSRange(location: 0, length: label?.length ?? 0))
        

        if entry.param2 > 0 {
           
            label?.addAttributes([.foregroundColor:UIColor.init(red: 255/255.0, green: 52/255.0, blue: 52/255.0, alpha: 1.0),.font:self.font], range:NSMakeRange(str.count + 4, str1.count - 3))
        }
        else if entry.param2 == 0 {
            label?.addAttributes([.foregroundColor:UIColor.white,.font:self.font], range: NSMakeRange(str.count, str1.count))
        }
        else{
            label?.addAttributes([.foregroundColor:UIColor.init(red: 0/255.0, green: 248/255.0, blue: 83/255.0, alpha: 1.0),.font:self.font], range: NSMakeRange(str.count + 4, str1.count - 3))
        }
        
        let strSize2 =  str1.size(withAttributes: _drawAttributes)
        let strSize1 =  str.size(withAttributes: _drawAttributes)
        let maxWidth = max(strSize1.width, strSize2.width)
        let totalHeight = strSize1.height +  strSize2.height + 6
        var size = CGSize()
        size.width = maxWidth + self.insets.left + self.insets.right
        size.height = totalHeight + self.insets.top + self.insets.bottom
        size.width = max(minimumSize.width, size.width)
        size.height = max(minimumSize.height, size.height)
        self.size = size
    }
    
    open func draw(context: CGContext, point: CGPoint)
    {
        guard let label = label else { return }
        let offset = self.offsetForDrawing(atPoint: point)
        let size = self.size
        
        var rect = CGRect(
            origin: CGPoint(
                x: point.x + offset.x,
                y: point.y + offset.y),
            size: size)
        rect.origin.x -= size.width / 2.0
        rect.origin.y -= size.height
        
        context.saveGState()

        context.setFillColor(color.cgColor)

        if offset.y > 0
        {
//            context.beginPath()
//            context.move(to: CGPoint(
//                x: rect.origin.x,
//                y: rect.origin.y + arrowSize.height))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x + (rect.size.width - arrowSize.width) / 2.0,
//                y: rect.origin.y + arrowSize.height))
//            //arrow vertex
//            context.addLine(to: CGPoint(
//                x: point.x,
//                y: point.y))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x + (rect.size.width + arrowSize.width) / 2.0,
//                y: rect.origin.y + arrowSize.height))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x + rect.size.width,
//                y: rect.origin.y + arrowSize.height))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x + rect.size.width,
//                y: rect.origin.y + rect.size.height))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x,
//                y: rect.origin.y + rect.size.height))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x,
//                y: rect.origin.y + arrowSize.height))
//            context.fillPath()
            
            context.beginPath()
            let rect2 = CGRect(x: rect.origin.x, y: rect.origin.y + arrowSize.height, width: rect.size.width, height: rect.size.height - arrowSize.height)
            let clipPath = UIBezierPath(roundedRect: rect2, cornerRadius: 5.0).cgPath
            context.addPath(clipPath)
            context.closePath()
            context.fillPath()
            
            // arraow vertex
            context.beginPath()
            let p1 = CGPoint(x: rect.origin.x + rect.size.width / 2.0 - arrowSize.width / 2.0, y: rect.origin.y + arrowSize.height + 1)
            context.move(to: p1)
            context.addLine(to: CGPoint(x: p1.x + arrowSize.width, y: p1.y))
            context.addLine(to: CGPoint(x: point.x, y: point.y))
            context.addLine(to: p1)
            
            context.fillPath()
        }
        else
        {
//            context.beginPath()
//            context.move(to: CGPoint(
//                x: rect.origin.x,
//                y: rect.origin.y))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x + rect.size.width,
//                y: rect.origin.y))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x + rect.size.width,
//                y: rect.origin.y + rect.size.height - arrowSize.height))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x + (rect.size.width + arrowSize.width) / 2.0,
//                y: rect.origin.y + rect.size.height - arrowSize.height))
//            //arrow vertex
//            context.addLine(to: CGPoint(
//                x: point.x,
//                y: point.y))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x + (rect.size.width - arrowSize.width) / 2.0,
//                y: rect.origin.y + rect.size.height - arrowSize.height))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x,
//                y: rect.origin.y + rect.size.height - arrowSize.height))
//            context.addLine(to: CGPoint(
//                x: rect.origin.x,
//                y: rect.origin.y))
//            context.fillPath()
            
            context.beginPath()
            let rect2 = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height - arrowSize.height)
            let clipPath = UIBezierPath(roundedRect: rect2, cornerRadius: 5.0).cgPath
            context.addPath(clipPath)
            context.closePath()
            context.fillPath()
            
            // arraow vertex
            context.beginPath()
            let p1 = CGPoint(x: rect.origin.x + rect.size.width / 2.0 - arrowSize.width / 2.0, y: rect.origin.y + rect.size.height - arrowSize.height - 1)
            context.move(to: p1)
            context.addLine(to: CGPoint(x: p1.x + arrowSize.width, y: p1.y))
            context.addLine(to: CGPoint(x: point.x, y: point.y))
            context.addLine(to: p1)
            
            context.fillPath()
        }
        
        if offset.y > 0 {
            rect.origin.y += self.insets.top + arrowSize.height
        } else {
            rect.origin.y += self.insets.top
        }

        rect.size.height -= self.insets.top + self.insets.bottom
        
        UIGraphicsPushContext(context)
        
        label.draw(in: rect)
        
        UIGraphicsPopContext()
        
        context.restoreGState()
    }
}
